<template>
  <div class="dress-manage-container">
    <el-card class="dress-manage-card">
      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-form :inline="true" :model="searchForm">
          <el-form-item label="搜索">
            <el-input
              v-model="searchForm.keyword"
              placeholder="婚纱名称"
              clearable
              @keyup.enter="handleSearch"
            />
          </el-form-item>
          <el-form-item label="类别">
            <el-select
              class="status-search"
              v-model="searchForm.category"
              placeholder="选择类别"
              clearable
            >
              <el-option label="婚纱" value="1" />
              <el-option label="晚礼服" value="2" />
              <el-option label="中式礼服" value="3" />
            </el-select>
          </el-form-item>
          <el-form-item label="风格">
            <el-select
              class="status-search"
              v-model="searchForm.style"
              placeholder="选择风格"
              clearable
            >
              <el-option label="简约" value="simple" />
              <el-option label="奢华" value="luxury" />
              <el-option label="复古" value="vintage" />
              <el-option label="现代" value="modern" />
              <el-option label="公主" value="princess" />
              <el-option label="鱼尾" value="mermaid" />
              <el-option label="A型" value="aline" />
              <el-option label="中式" value="chinese" />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select
              class="status-search"
              v-model="searchForm.status"
              placeholder="选择状态"
              clearable
            >
              <el-option label="可租赁" value="available" />
              <el-option label="已租出" value="rented" />
              <el-option label="维护中" value="maintaining" />
              <el-option label="已下架" value="retired" />
            </el-select>
          </el-form-item>
          <el-form-item label="价格区间">
            <el-input-number
              v-model="searchForm.minPrice"
              :min="0"
              :step="100"
              placeholder="最低价"
              style="width: 130px"
            />
            <span class="price-separator">-</span>
            <el-input-number
              v-model="searchForm.maxPrice"
              :min="0"
              :step="100"
              placeholder="最高价"
              style="width: 130px"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
            <el-button type="success" @click="handleAdd">添加婚纱</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 婚纱列表 -->
      <el-table v-loading="loading" :data="dressList" style="width: 100%" border>
        <el-table-column label="婚纱信息" min-width="300">
          <template #default="{ row }">
            <div class="dress-info">
              <el-image :src="row.photos?.[0]" fit="cover" class="dress-image" />
              <div class="info-detail">
                <div class="name">{{ row.name }}</div>
                <div class="tags">
                  <el-tag size="small" type="success">{{ getCategoryLabel(row.category) }}</el-tag>
                  <el-tag
                    v-for="style in row.styles"
                    :key="style"
                    size="small"
                    type="info"
                    class="style-tag"
                  >
                    {{ getStyleLabel(style) }}
                  </el-tag>
                </div>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="尺码" width="150">
          <template #default="{ row }">
            <el-tag v-for="size in row.sizes" :key="size" size="small" class="size-tag">
              {{ size }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="价格" width="180">
          <template #default="{ row }">
            <div class="price-info">
              <div>租赁价：¥{{ row.price }}</div>
              <div>押金：¥{{ row.deposit }}</div>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="rent_count" label="租赁次数" width="100" align="center" />

        <el-table-column label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">
              {{ getStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)"> 编辑 </el-button>
            <el-button type="success" link @click="handleViewImages(row)"> 图片管理 </el-button>
            <el-button
              :type="row.is_active ? 'danger' : 'success'"
              link
              @click="handleToggleStatus(row)"
            >
              {{ row.is_active ? '下架' : '上架' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <!-- 编辑对话框 -->
      <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑婚纱' : '添加婚纱'" width="600px">
        <el-form ref="formRef" :model="editForm" :rules="rules" label-width="100px">
          <el-form-item label="名称" prop="name">
            <el-input v-model="editForm.name" />
          </el-form-item>

          <el-form-item label="类别" prop="category">
            <el-select v-model="editForm.category">
              <el-option label="婚纱" value="1" />
              <el-option label="晚礼服" value="2" />
              <el-option label="中式礼服" value="3" />
            </el-select>
          </el-form-item>

          <el-form-item label="风格" prop="style">
            <el-select v-model="editForm.styles" multiple>
              <el-option label="简约" value="simple" />
              <el-option label="奢华" value="luxury" />
              <el-option label="复古" value="vintage" />
              <el-option label="现代" value="modern" />
              <el-option label="公主" value="princess" />
              <el-option label="鱼尾" value="mermaid" />
              <el-option label="A型" value="aline" />
              <el-option label="中式" value="chinese" />
            </el-select>
          </el-form-item>

          <el-form-item label="尺码" prop="size">
            <el-select v-model="editForm.sizes" multiple>
              <el-option label="XS" value="XS" />
              <el-option label="S" value="S" />
              <el-option label="M" value="M" />
              <el-option label="L" value="L" />
              <el-option label="XL" value="XL" />
              <el-option label="XXL" value="XXL" />
            </el-select>
          </el-form-item>

          <el-form-item label="颜色" prop="color">
            <el-select v-model="editForm.colors" multiple>
              <el-option label="白色" value="white" />
              <el-option label="香槟色" value="champagne" />
              <el-option label="粉色" value="pink" />
              <el-option label="红色" value="red" />
            </el-select>
          </el-form-item>

          <el-form-item label="租赁价格" prop="price">
            <el-input-number v-model="editForm.price" :min="0" :step="100" />
          </el-form-item>

          <el-form-item label="押金" prop="deposit">
            <el-input-number v-model="editForm.deposit" :min="0" :step="100" />
          </el-form-item>

          <el-form-item label="描述" prop="description">
            <el-input v-model="editForm.description" type="textarea" :rows="3" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSave" :loading="saveLoading"> 保存 </el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 图片管理对话框 -->
      <el-dialog v-model="imagePreviewDialogVisible">
        <img w-full :src="imagePreviewDialogImageUrl" alt="Preview Image" />
      </el-dialog>

      <el-dialog v-model="imageDialogVisible" title="图片管理" width="800px">
        <div v-loading="uploadLoading" class="upload-container">
          <el-upload
            class="image-uploader"
            action="#"
            list-type="picture-card"
            :auto-upload="false"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-change="handleImageChange"
            :before-upload="beforeUpload"
            :file-list="photosList"
            multiple
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="imageDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSaveImages" :loading="saveLoading">
              保存
            </el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules, UploadUserFile } from 'element-plus'
import type { Dress, DressQuery, DressCategory, DressStyle, DressStatus } from '@/types/dress'
import { beforeUpload } from '@/utils/upload'
import type { FileItem, UploadFile } from '@/types/upload'
import { v4 as uuidv4 } from 'uuid'
import { uploadWeddings } from '@/api/upload'
import Logger from '@/utils/logger'
import {
  updateDressStatus,
  updateDressPhotos,
  updateDress,
  createDress,
  getDresses,
} from '@/api/dress'

// 搜索表单
const searchForm = reactive<DressQuery>({
  keyword: '',
  category: undefined,
  style: undefined,
  status: undefined,
  minPrice: undefined,
  maxPrice: undefined,
  page: 1,
  pageSize: 10,
})

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 加载状态
const loading = ref(false)
const saveLoading = ref(false)

// 对话框相关
const imagePreviewDialogImageUrl = ref('')
const imagePreviewDialogVisible = ref(false)
const dialogVisible = ref(false)
const imageDialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref<FormInstance>()

// 图片管理相关
const uploadLoading = ref(false)
const photosList = ref<UploadUserFile[]>([])

// 编辑表单
const editForm = reactive<Partial<Dress>>({
  id: 0,
  name: '',
  category: 1,
  styles: [],
  sizes: [],
  colors: [],
  price: 0,
  deposit: 0,
  description: '',
  photos: [],
  rent_count: 0,
})

// 表单验证规则
const rules = reactive<FormRules>({
  name: [
    { required: true, message: '请输入婚纱名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' },
  ],
  category: [{ required: true, message: '请选择类别', trigger: 'change' }],
  styles: [{ required: true, type: 'array', message: '请选择风格', trigger: 'change' }],
  sizes: [{ required: true, type: 'array', message: '请选择尺码', trigger: 'change' }],
  colors: [{ required: true, type: 'array', message: '请选择颜色', trigger: 'change' }],
  price: [{ required: true, message: '请输入租赁价格', trigger: 'blur' }],
  deposit: [{ required: true, message: '请输入押金', trigger: 'blur' }],
})

// 婚纱列表数据
const dressList = ref<Dress[]>([])

// 获取类别标签文本
const getCategoryLabel = (category: DressCategory) => {
  const labels: Record<DressCategory, string> = {
    1: '婚纱',
    2: '晚礼服',
    3: '中式礼服',
  }
  return labels[category]
}

// 获取风格标签文本
const getStyleLabel = (style: DressStyle) => {
  const labels: Record<DressStyle, string> = {
    simple: '简约',
    luxury: '奢华',
    vintage: '复古',
    modern: '现代',
    princess: '公主',
    mermaid: '鱼尾',
    aline: 'A型',
    chinese: '中式',
  }
  return labels[style]
}

// 获取状态标签类型
const getStatusTagType = (status: DressStatus) => {
  const types: Record<DressStatus, string> = {
    1: 'success',
    2: 'warning',
    3: 'info',
    4: 'danger',
  }
  return types[status]
}

// 获取状态标签文本
const getStatusLabel = (status: DressStatus) => {
  const labels: Record<DressStatus, string> = {
    1: '可租赁',
    2: '已租出',
    3: '维护中',
    4: '已下架',
  }
  return labels[status]
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchData()
}

// 重置搜索
const resetSearch = () => {
  searchForm.keyword = ''
  searchForm.category = undefined
  searchForm.style = undefined
  searchForm.status = undefined
  searchForm.minPrice = undefined
  searchForm.maxPrice = undefined
  handleSearch()
}

// 处理分页
const handleSizeChange = (val: number) => {
  pageSize.value = val
  fetchData()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  fetchData()
}

// 添加婚纱
const handleAdd = () => {
  isEdit.value = false
  Object.assign(editForm, {
    name: '',
    category: '',
    style: [],
    size: [],
    color: [],
    price: 0,
    deposit: 0,
    description: '',
  })
  dialogVisible.value = true
}

// 编辑婚纱
const handleEdit = (row: Dress) => {
  isEdit.value = true
  Object.assign(editForm, {
    id: row.id,
    name: row.name,
    category: String(row.category),
    styles: row.styles || [],
    sizes: row.sizes || [],
    colors: row.colors || [],
    price: row.price,
    deposit: row.deposit,
    description: row.description,
    photos: row.photos || [],
  })
  dialogVisible.value = true
}

// MARK: 图片管理
// 查看图片
const handleViewImages = (row: Dress) => {
  editForm.id = row.id
  // 将现有图片转换为 UploadUserFile 格式
  if (row.photos) {
    photosList.value = row.photos?.map((url, index) => {
      return {
        name: `图片${index + 1}`,
        url: url,
      } as UploadUserFile
    })
  }
  imageDialogVisible.value = true
}

// 处理图片上传
const handleImageChange = (file: UploadFile) => {
  if (!beforeUpload(file.raw)) return

  // 创建预览URL
  const reader = new FileReader()
  reader.readAsDataURL(file.raw)
  reader.onload = async () => {
    const newFile: FileItem = {
      uid: uuidv4(),
      name: file.name,
      url: reader.result as string,
      status: 'ready',
      raw: file.raw,
    }

    try {
      if (!newFile.raw) {
        ElMessage.error('请选择文件')
        return
      }

      newFile.status = 'uploading'
      newFile.percentage = 0

      const response = await uploadWeddings([newFile.raw], (percentage) => {
        newFile.percentage = percentage
      })

      newFile.status = 'success'
      photosList.value.push({
        name: response.data.data.files[0].filename,
        url: response.data.data.files[0].url,
      } as UploadUserFile)
      ElMessage.success('上传成功')
    } catch (error) {
      newFile.status = 'error'
      ElMessage.error('上传失败')
      Logger.error('上传失败', error)
    }
  }
}

const handleRemove = (file: UploadUserFile) => {
  const index = photosList.value.findIndex((item) => item.url === file.url)
  if (index > -1) {
    photosList.value.splice(index, 1)
  }
}

const handlePictureCardPreview = (file: UploadUserFile) => {
  imagePreviewDialogImageUrl.value = file.url!
  imagePreviewDialogVisible.value = true
}

// 保存图片
const handleSaveImages = async () => {
  saveLoading.value = true
  try {
    const uploadPhotos = photosList.value.map((item) => item.url!)
    const response = await updateDressPhotos(editForm.id!, {
      photos: uploadPhotos,
    })
    Logger.info('保存图片成功', response)
    ElMessage.success('保存成功')
    imageDialogVisible.value = false
    fetchData()
  } catch (error) {
    Logger.error('保存图片失败', error)
    ElMessage.error('保存失败')
  } finally {
    saveLoading.value = false
  }
}

// 切换状态
const handleToggleStatus = async (row: Dress) => {
  try {
    await ElMessageBox.confirm(`确定要${row.is_active ? '上架' : '下架'}该婚纱吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    await updateDressStatus(row.id)
    ElMessage.success('操作成功')
    fetchData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
    }
  }
}

// 保存婚纱信息
const handleSave = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      saveLoading.value = true
      if (isEdit.value) {
        try {
          await updateDress(editForm.id!, {
            name: editForm.name,
            category: Number(editForm.category),
            styles: editForm.styles,
            sizes: editForm.sizes,
            colors: editForm.colors,
            price: editForm.price,
            deposit: editForm.deposit,
            description: editForm.description,
          })

          ElMessage.success('保存成功')
          dialogVisible.value = false
          fetchData()
        } catch (error) {
          ElMessage.error('保存失败')
        } finally {
          saveLoading.value = false
        }
      } else {
        try {
          await createDress({
            name: editForm.name!,
            category: Number(editForm.category),
            styles: editForm.styles!,
            sizes: editForm.sizes!,
            colors: editForm.colors!,
            price: editForm.price!,
            deposit: editForm.deposit!,
            description: editForm.description!,
          })

          ElMessage.success('创建婚纱成功')
          dialogVisible.value = false
          fetchData()
        } catch (error) {
          ElMessage.error('创建婚纱失败')
        } finally {
          saveLoading.value = false
        }
      }
    }
  })
}

// 获取数据
const fetchData = async () => {
  loading.value = true
  try {
    const { data } = await getDresses({
      keyword: searchForm.keyword,
      category: searchForm.category,
      style: searchForm.style,
      status: searchForm.status,
      minPrice: searchForm.minPrice,
      maxPrice: searchForm.maxPrice,
      page: currentPage.value,
      pageSize: pageSize.value,
    })
    dressList.value = data.data.items
    total.value = data.data.meta.total
  } catch (error) {
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.dress-manage-container {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
  min-height: calc(100vh - 200px);
  box-sizing: border-box;
}

.dress-manage-card {
  margin-top: 0;
}

.search-bar {
  margin-bottom: 20px;
}

.price-separator {
  margin: 0 10px;
}

.dress-info {
  display: flex;
  gap: 15px;
}

.dress-image {
  width: 100px;
  height: 150px;
  border-radius: 4px;
}

.info-detail {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.name {
  font-size: 16px;
  font-weight: bold;
}

.code {
  color: #666;
  font-size: 13px;
}

.tags {
  display: flex;
  gap: 5px;
  flex-wrap: wrap;
}

.style-tag {
  margin-left: 5px;
}

.size-tag {
  margin-right: 5px;
  margin-bottom: 5px;
}

.price-info {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.image-uploader {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

:deep(.el-upload--picture-card) {
  width: 150px;
  height: 150px;
  line-height: 150px;
}

.status-search {
  width: 100px;
}
</style>
